<template>
	<div >
		<div class="system-user-search mb15">
			<el-form :model="param.dataForm" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row>
					<el-col :span="8">
							<el-form-item label="appId" prop="appId">
								<el-input  v-model="param.dataForm.appId" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
							<el-form-item label="接入方名称" prop="appName">
								<el-input  v-model="param.dataForm.appName" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="btnStyle">
			<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			<el-button type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
			<el-button type="danger" icon="ele-Delete" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
		</div>
		<el-table :data="dataList" @selection-change="selectionChangeHandle" style="width: 100%">
			<el-table-column prop="id" type="selection" header-align="center" align="center" width="50"/>
			<el-table-column prop="appName" header-align="center" align="center" label="接入方名称"/>
			<el-table-column prop="appId" header-align="center" align="center" label="appId"/>
			<el-table-column prop="appStatus" header-align="center" align="center" label="状态" column-key="1001" :formatter="formatStatus"/>
			<el-table-column prop="encryption" header-align="center" align="center" label="加密算法" column-key="API_ENC" :formatter="formatStatus"/>
			<el-table-column prop="encBean" header-align="center" align="center" label="扩展算法bean"/>
			<el-table-column prop="ipWhite" header-align="center" align="center" label="是否启用白名单" column-key="1008" :formatter="formatStatus"/>
			<el-table-column prop="whiteList" header-align="center" align="center" label="白名单地址"/>
			<el-table-column label="操作" show-overflow-tooltip width="140">
				<template #default="scope">
					<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
					<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog :close-on-click-modal="false" :title="!submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-form :model="submitForm" :rules="submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit" label-width="120px">
				<el-row >
					<el-col :span="12">
						<el-form-item label="接入方名称" prop="appName" >
							<el-input v-model="submitForm.appName" placeholder="接入方名称" maxlength="100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="唯一编号" prop="appId" >
							<el-input v-model="submitForm.appId" placeholder="唯一编号" maxlength="100"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row >
					<el-col :span="12">
						<el-form-item label="算法" prop="encryption" >
							<DicSelect v-model="submitForm.encryption" placeholder="请选择" dicCode="API_ENC" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="扩展算法bean" prop="encBean" v-if="submitForm.encryption === 'extend'">
							<el-input v-model="submitForm.encBean" placeholder="扩展算法bean" maxlength="200"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row >
					<el-col :span="12">
						<el-form-item label="状态" prop="appStatus" >
							<DicSelect v-model="submitForm.appStatus" placeholder="请选择" dicCode="1001" :excludeIsKey="['100103']" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="算法类型" prop="cryptType" v-if="submitForm.encryption === 'extend'">
							<DicSelect v-model="submitForm.cryptType" placeholder="请选择" dicCode="API_ENC_TYPE" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row >
					<el-col :span="24">
						<el-form-item label="秘钥/公钥" prop="appSecret" >
							<el-input v-model="submitForm.appSecret" placeholder="秘钥/公钥" maxlength="2000">
								<template #append>
									<el-button type="button" @click="getSecret()">生成秘钥</el-button>
								</template>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row  v-if="submitForm.cryptType === '2'" >
					<el-col :span="24">
						<el-form-item label="私钥" prop="appPrivateSecret" >
							<el-input v-model="submitForm.appPrivateSecret" placeholder="私钥" maxlength="2000"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row >
					<el-col :span="12">
						<el-form-item label="是否启用白名单" prop="ipWhite" >
							<DicSelect v-model="submitForm.ipWhite" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="白名单地址" prop="whiteList" v-if="submitForm.ipWhite === '1'"  >
							<el-input v-model="submitForm.whiteList" placeholder="白名单地址" maxlength="1000"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent,watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {apiMngApi} from '/@/api/apimngapi'
import { getCodeList } from '/@/utils/cacheDict'
export default defineComponent({
	name: 'systemDic',
	setup () {
		const state = reactive({
			listLoading: false,
			listSelectLoading: false,
			dataList: [],
			dataListSelect: [],
			dataDictionaryList: {},
			dataListSelections: [],
			total: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				dataForm: {
					appId: '',
					appName: ''
				}
			},
			paramSelect: {
				page: 1,
				limit: 10,
				dataForm: {
					classCode: '',
					className: ''
				}
			},
			addOrUpdateVisible: false,
			visibleSelect: false,
			submitForm: {
				id: '',
				appName: '',
				appId: '',
				appSecret: '',
				appPrivateSecret: '',
				appStatus: '',
				encryption: '',
				cryptType: '',
				encBean: '',
				ipWhite: '',
				whiteList: '',
				creater: '',
				createTime: '',
				modUser: '',
				modTime: '',
			},
			submitFormRule: {
				appName: { required: true, message: '名称不能为空', trigger: 'blur' },
				appId: { required: true, message: 'appId不能为空', trigger: 'blur' },
				appSecret: { required: true, message: '秘钥不能为空', trigger: 'blur' },
				appStatus: { required: true, message: '状态不能为空', trigger: 'change' },
				encryption: { required: true, message: '算法不能为空', trigger: 'change' },
				encBean: { required: false, message: '算法bean不能为空', trigger: 'blur' },
				cryptType: { required: false, message: '请选择算法类型', trigger: 'change' },
				ipWhite: { required: true, message: '是否白名单不能为空', trigger: 'change' },
				appPrivateSecret: { required: false, message: '私钥不能为空', trigger: 'change' }
			}
		})
		// 页面加载时
		onMounted(() => {
			// 数据字典
			getCodeList(state, ['1001', '1008', 'API_ENC'])
			// 列表查询
			loadList()
		})
		const queryFormRef = ref<FormInstance>()
		const ruleFormRef = ref<FormInstance>();
		//查询
		const loadList = () => {
			state.listLoading = true
			apiMngApi().queryPage(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})	
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}
		const selectionChangeHandle = (val:any) => {
			state.dataListSelections = val
		}
		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}
		
		const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
			if(Object.keys(state.dataDictionaryList).length>0){
				if (cellValue) {
				return state.dataDictionaryList[column.columnKey][cellValue];
				}
			}
		}

		const getSecret = () => {
			if(state.submitForm.encryption === 'extend'){
				if(!state.submitForm.encBean){
					ElMessage.error("请填写扩展算法bean")
					return
				}
				if(!state.submitForm.cryptType){
					ElMessage.error("请选择算法类型")
					return
				}
			}
			let data = state.submitForm
			apiMngApi().getSecretByAlgorithm(data).then(data => {
				console.log(data)
				if (data && data.code === 0) {
					state.submitForm.appSecret = data.data.appSecret
					state.submitForm.appPrivateSecret = data.data.appPrivateSecret
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(res => {
				ElMessage.error("获取秘钥失败")
			})
		}

		watch(() => state.submitForm.encryption, (val:string) => {
			if(val === 'extend'){
				state.submitFormRule.encBean.required = true
				state.submitFormRule.cryptType.required = true
			}else if(val === 'SM2' || val === 'RSA'){
				state.submitForm.cryptType = '2'
			}else{
				state.submitForm.cryptType = ''
				state.submitFormRule.encBean.required = false
				state.submitFormRule.cryptType.required = false
			}
		})

		watch(() => state.submitForm.cryptType, (val:string) => {
			if(val === '2'){
				state.submitFormRule.appPrivateSecret.required = true
			}
		})

		//打开新增弹窗
		const addOrUpdateHandle = () => {
			state.submitForm = {
				id: '',
				appName: '',
				appId: '',
				appSecret: '',
				appPrivateSecret: '',
				appStatus: '',
				encryption: '',
				cryptType: '',
				encBean: '',
				ipWhite: '',
				whiteList: '',
				creater: '',
				createTime: '',
				modUser: '',
				modTime: '',
			}
			state.addOrUpdateVisible = true
		}
		//打开修改弹窗
		const updateHandle = (row: any | undefined) => {
			state.submitForm = {
				id: '',
				appName: '',
				appId: '',
				appSecret: '',
				appPrivateSecret: '',
				appStatus: '',
				encryption: '',
				cryptType: '',
				encBean: '',
				ipWhite: '',
				whiteList: '',
				creater: '',
				createTime: '',
				modUser: '',
				modTime: '',
			}
			let selectId = ''
			if(!row){
				selectId = state.dataListSelections[0].id
				state.submitForm = state.dataListSelections[0]
			} else {
				state.submitForm = row
				selectId = row.id
			}
			apiMngApi().getApiMngById(selectId).then(data => {
				if (data && data.code === 0) {
					state.submitForm = data.data
				}
			})
			state.addOrUpdateVisible = true
			
		}
		//打开删除弹窗
		const deleteHandle = (id: string | undefined) => {
			var ids = id ? [id] : state.dataListSelections.map(item => {
				return item.id
			})
			if (!ids) {
				ElMessage.error('请选择记录！')
				return
			}
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				apiMngApi().deleteApiMng(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功')
						loadList();
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("删除失败")
				})
			})
		}

		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					// 提交数据
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if(!state.submitForm.id) {
						// 新增
						apiMngApi().saveApiMng(state.submitForm).then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 列表查询
								loadList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					} else{
						apiMngApi().updateApiMng(state.submitForm).then((data) => {
							console.log(data)
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 列表查询
								loadList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}

		return {
			loadList,
			reSetForm,
			queryFormRef,
			selectionChangeHandle,
			onHandleSizeChange,
			onHandleCurrentChange,
			formatStatus,
			addOrUpdateHandle,
			updateHandle,
			deleteHandle,
			dataFormSubmit,
			ruleFormRef,
			getSecret,
			...toRefs(state),
		}
	}
})
</script>